﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using StudentBackendService.Exceptions;
using StudentBackendService.ViewObjects;

namespace StudentBackendService.Filters
{
    public class ExceptionFilter : IActionFilter, IOrderedFilter
    {
        private readonly ILogger<ExceptionFilter> _logger;

        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            _logger = logger;
        }   

        public int Order => int.MaxValue - 10;

        public void OnActionExecuting(ActionExecutingContext context)
        {

        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            var res = new Response();
            if (context.Exception == null)
            {
                return;
            }

            if (context.Exception is LogicException logicException)
            {
                res.Message = logicException.GetMessage();
                res.Code = logicException.GetCode();
                goto Handler;
            }

            if (context.Exception is ArgumentException argumentException)
            {
                res.Data = null;
                res.Message = argumentException.Message;
                res.Code = 400;
                goto Handler;
            }

            Handler:
            res.Data = null;
            context.Result = new ObjectResult(res) { StatusCode = 200 };
            context.ExceptionHandled = true;
            _logger.LogError(context.Exception.Message);
            _logger.LogError(context.Exception.StackTrace);
        }
    }
}
